package DFS;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Solution40 {


    public static void main(String[] args) {
        int[] nums = new int[]{2, 5, 2, 1, 2};
        System.out.println(combinationSum2(nums, 5));
    }


    public static List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> chain = new ArrayList<>();
        dfs(candidates, target, new boolean[candidates.length], 0, chain, res);
        return res;
    }

    public static void dfs(int[] nums, int target, boolean[] pb, int index, List<Integer> chain, List<List<Integer>> res) {

        if (target < 0) {
            return;
        }
        if (target == 0) {
            List<Integer> list = new ArrayList<>(chain);
            Collections.sort(list);
            if (!res.contains(list)) {
                res.add(list);
            }
            return;
        }

        for (int i = index; i < nums.length; i++) {
            if (target - nums[i] < 0) {
                break;
            }
            if (i > index &&
                    !pb[i] && nums[i] == nums[i - 1]) {
                continue;
            }
            pb[i] = true;
            chain.add(nums[i]);
            target -= nums[i];
            System.out.println("dfs前i=" + i + "index=" + index + " chain" + chain + "剩下" + target);
            dfs(nums, target, pb, i + 1, chain, res);
            System.out.println("dfs后i=" + i + "index=" + index + " chain" + chain + "剩下" + target);
            target += nums[i];
            pb[i] = false;
            chain.remove(chain.size() - 1);
        }
    }


}
